package com.chaodev.base.controller;

import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.service.IDictService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import com.chaodev.base.utils.TreeHelper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping(value = "/dict")
public class DictController {

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Autowired
    private IDictService dictService;


    @PostMapping(value = "/getDictList")
    @ApiOperation(value = "字典列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result dictQuery(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //默认分页设置
            if (null == dataPage.getPage()) {
                dataPage.setPage(1);
            }
            if (null == dataPage.getRows()) {
                dataPage.setRows(20);
            }
            if (null == dataPage.getSort()) {
                dataPage.setSort("");
            }
            switch (dataPage.getSort()){
                case "dictName":
                    dataPage.setSort("DICT_NAME");
                    break;
                case "dictCode":
                    dataPage.setSort("DICT_CODE");
                    break;
                case "createTime":
                    dataPage.setSort("CREATE_TIME");
                    break;
                default:
                    dataPage.setSort("CREATE_TIME");
                    break;
            }
            if(!StringUtils.hasText(dataPage.getOrder())){
                dataPage.setOrder("DESC");
            }
            //查询字典分页列表
            PageInfo<Dict> pageInfo = dictService.dictQuery(dataPage);
            Map<String, Object> map = new HashMap<>(2);
            map.put("total", pageInfo.getTotal());
            map.put("rows", pageInfo.getList());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(map);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "字典列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "字典列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    /**
     * @Description: 功能新增
     * @Author: xy
     * @CreateDate: 2019/12/26 20:04
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 20:04
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/insertDict")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典新增")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result insertDict(@RequestBody @ApiParam(value = "功能信息") Dict dict, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dict.setCreateBy(userInfo.getUserId());
            Integer validResult=dictService.validateDict(dict);
            if(validResult>0){
                result.setCode(-1);
                result.setMsg("已存在相同的编码或名称！");
                return result;
            }
            boolean flag = dictService.dictAdd(dict);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(dict.toString(), "字典新增", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dict.toString(), "字典新增", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/updateDict")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典编辑")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result updateDict(@RequestBody @ApiParam(value = "功能信息") Dict dict, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dict.setUpdateBy(userInfo.getUserId());
            Integer validResult=dictService.validateDict(dict);
            if(validResult>0){
                result.setCode(-1);
                result.setMsg("已存在相同的编码或名称！");
                return result;
            }
            boolean flag = dictService.dictUpdate(dict);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(dict.toString(), "字典编辑", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dict.toString(), "字典编辑", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 功能删除
     * @Author: xy
     * @CreateDate: 2019/12/26 16:24
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 16:24
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/deleteDict")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典删除")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result deleteDict(@RequestBody @ApiParam(value = "功能消息") Dict dict, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String,Object> map=new HashMap<>(1);
            map.put("id",dict.getId());
            boolean flag = dictService.dictDelete(map);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(dict.toString(), "字典删除", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dict.toString(), "字典删除", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getDictInfo")
    @ApiOperation(value = "字典详情")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getDictInfo(@RequestBody @ApiParam(value = "查询详情") Dict dict, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String,Object> map=new HashMap<>(1);
            map.put("id",dict.getId());
            //查询字典分页列表
            Dict dictInfo = dictService.getDictInfo(map);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(dictInfo);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dict.toString(), "字典详情", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dict.toString(), "字典详情", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }



    @PostMapping(value = "/getDictDetailList")
    @ApiOperation(value = "字典项列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result dictDetailQuery(@RequestBody @ApiParam(value = "分页传入参数") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //默认分页设置
//            if (null == dataPage.getPage()) {
//                dataPage.setPage(1);
//            }
//            if (null == dataPage.getRows()) {
//                dataPage.setRows(20);
//            }
//            if(!StringUtils.hasText(dataPage.getSort())){
//                dataPage.setOrder("SORT_ORDER");
//            }
//            if(!StringUtils.hasText(dataPage.getOrder())){
//                dataPage.setOrder("ASC");
//            }
            //查询字典分页列表
//            PageInfo<DictDetail> pageInfo = dictService.dictDetailQuery(dataPage);
            List<ZtreeModel> pageInfo = dictService.dictDetailQuery(dictDetail);
//            Map<String, Object> map = new HashMap<>(2);

//            map.put("total", pageInfo.getTotal());
//            map.put("rows", pageInfo.getList());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(pageInfo);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dictDetail.toString(), "字典项列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 功能新增
     * @Author: xy
     * @CreateDate: 2019/12/26 20:04
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 20:04
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/insertDictDetail")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典项新增")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result insertDictDetail(@RequestBody @ApiParam(value = "功能信息") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dictDetail.setCreateBy(userInfo.getUserId());
            Integer validResult=dictService.validateDictDetail(dictDetail);
            if(validResult>0){
                result.setCode(-1);
                result.setMsg("已存在相同的编码或名称！");
                return result;
            }
            boolean flag = dictService.insertDictDetail(dictDetail);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(dictDetail.toString(), "字典项新增", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项新增", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/updateDictDetail")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典项编辑")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result updateDictDetail(@RequestBody @ApiParam(value = "功能信息") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dictDetail.setUpdateBy(userInfo.getUserId());
            Integer validResult=dictService.validateDictDetail(dictDetail);
            if(validResult>0){
                result.setCode(-1);
                result.setMsg("已存在相同的编码或名称！");
                return result;
            }
            boolean flag = dictService.updateDictDetail(dictDetail);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(dictDetail.toString(), "字典项编辑", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项编辑", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 功能删除
     * @Author: xy
     * @CreateDate: 2019/12/26 16:24
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/26 16:24
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/deleteDictDetail")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "字典项删除")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result deleteDictDetail(@RequestBody @ApiParam(value = "功能消息") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String,Object> map=new HashMap<>(1);
            map.put("id",dictDetail.getId());
            boolean flag = dictService.deleteDictDetail(map);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(dictDetail.toString(), "字典项删除", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项删除", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getDictDetailInfo")
    @ApiOperation(value = "字典详情获取")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getDictDetailInfo(@RequestBody @ApiParam(value = "查询详情") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String,Object> map=new HashMap<>(1);
            map.put("id",dictDetail.getId());
            //查询字典分页列表
            DictDetail dictInfo = dictService.getDictDetailInfo(map);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(dictInfo);
            result.setCode(0);
            //记录日志
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dictDetail.toString(), "字典项详情获取", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项详情获取", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getDictDetailTreeList")
    @ApiOperation(value = "字典项树形列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result dictDetailTreeList(@RequestBody @ApiParam(value = "字典类型") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            List<ZtreeModel> pageInfo = dictService.dictDetailQuery(dictDetail);
            List<ElementTreeModel> elementTreeModelList=new ArrayList<>();
            if(!pageInfo.isEmpty()){
                for(ZtreeModel item:pageInfo){
                    ElementTreeModel model=new ElementTreeModel();
                    model.setId(String.valueOf(item.getId()));
                    model.setParentId(String.valueOf(item.getPid()));
                    model.setValue(item.getValue());
                    model.setLabel(item.getName());
                    elementTreeModelList.add(model);
                }
                elementTreeModelList= TreeHelper.getElementTreeInfo(elementTreeModelList);
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(elementTreeModelList);
            result.setCode(ResultEnum.SUCCESS.getCode());
            //记录日志
            Result logResult = new Result();
            logResult.setCode(ResultEnum.SUCCESS.getCode());
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dictDetail.toString(), "字典项列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dictDetail.toString(), "字典项列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getDictDetailTreeListOut")
    @ApiOperation(value = "字典项树形列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result dictDetailTreeListOut(@RequestBody @ApiParam(value = "字典类型") DictDetail dictDetail, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        UserInfo userInfo = new UserInfo();
        List<ZtreeModel> pageInfo = dictService.dictDetailQuery(dictDetail);
        List<ElementTreeModel> elementTreeModelList=new ArrayList<>();
        if(!pageInfo.isEmpty()){
            for(ZtreeModel item:pageInfo){
                ElementTreeModel model=new ElementTreeModel();
                model.setId(String.valueOf(item.getId()));
                model.setParentId(String.valueOf(item.getPid()));
                model.setValue(item.getValue());
                model.setLabel(item.getName());
                elementTreeModelList.add(model);
            }
            elementTreeModelList= TreeHelper.getElementTreeInfo(elementTreeModelList);
        }
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setData(elementTreeModelList);
        result.setCode(ResultEnum.SUCCESS.getCode());
        //记录日志
        Result logResult = new Result();
        logResult.setCode(ResultEnum.SUCCESS.getCode());
        //不记录返回数据，只做标识
        logResult.setMsg("数据获取成功");
        logResult.setServerID(result.getServerID());
        logService.logAdd(dictDetail.toString(), "字典项列表", "SUCCESS", logResult.toString(), userInfo, request);
        return result;
    }
}
